package com.itheima.job;

import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.db.Movement;
import com.itheima.domain.db.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 定时任务
 * @author zsk
 * @create 2022-03-27-17:14
 */
@Component
public class RedisToMongoJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")//测试使用一分钟
    public void movementJob(){
        System.out.println("推荐动态start...");
        //从Redis中取出推荐动态所有的key
        Set<String> keys = stringRedisTemplate.keys("MOVEMENTS_RECOMMEND_*");

        //遍历
        for (String key : keys) {
            //从key中获取用户id
            String userIdStr = key.replace("MOVEMENTS_RECOMMEND_", "");
            long userId = Long.parseLong(userIdStr);

            //获取推荐给此用户的动态id
            String pidsStr = stringRedisTemplate.opsForValue().get(key);
            //是一串字符串，中间使用,隔开
            String[] pidArray = pidsStr.split(",");
            //先删除Redis中存储的key
            stringRedisTemplate.delete(key);

            //删除RecommendMovement推荐给此用户的动态
            mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)), RecommendMovement.class);

            //遍历pidArray
            for (String pidStr : pidArray) {
                //转换pid为Long类型
                long pid = Long.parseLong(pidStr);

                //同步到mongo表中
                RecommendMovement recommendMovement = new RecommendMovement();
                recommendMovement.setCreated(System.currentTimeMillis());//当前时间
                recommendMovement.setUserId(userId);//推荐用户id
                recommendMovement.setPid(pid);//动态id
                Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(pid)), Movement.class);
                recommendMovement.setPublishId(movement.getId());//movement的主键id
                recommendMovement.setScore(RandomUtil.randomDouble(70,90));//推荐得分
                //保存
                mongoTemplate.save(recommendMovement);
            }
            System.out.println("推荐动态end...");

        }
    }
}
